import * as Vuex from 'vuex'
import {getAllCampus, GetAllRoom} from '@/api'

export default Vuex.createStore({
	state: {
		campusList: [], conferenceRoomList: [], userCampus: localStorage.getItem('WFITCampus') || '', role: (() => {
			const stored = localStorage.getItem('WFITRole')
			const parsed = parseInt(stored, 10)
			return isNaN(parsed) ? 0 : parsed
		})(),
	}, mutations: {
		setUserCampus(state, userCampus) {
			state.userCampus = userCampus
			localStorage.setItem('WFITCampus', userCampus)
		}, setCampusList(state, campusList) {
			state.campusList = campusList
		}, setConferenceRoomList(state, conferenceRoomList) {
			state.conferenceRoomList = conferenceRoomList
		}, setRole(state, role) {
			const parsed = Number.isInteger(role) ? role : parseInt(role, 10)
			state.role = isNaN(parsed) ? 0 : parsed
			localStorage.setItem('WFITRole', state.role.toString())
		},
	}, actions: {
		fetchCampusList({commit}) {
			// 调用 getAllCampus 方法获取校区列表数据
			getAllCampus().then((res) => {
				if (res.code === 200 && res.data.length !== 0) {
					const campusList = res.data
					commit('setCampusList', campusList)
				} else {
					commit('setCampusList', [])
				}
			})
		}, fetchConferenceRoomList({commit}) {
			GetAllRoom().then((res) => {
				if (res.code === 200 && res.data.length !== 0) {
					const conferenceRoomList = res.data
					commit('setConferenceRoomList', conferenceRoomList)
				} else {
					commit('setConferenceRoomList', [])
				}
			})
		}
	}, getters: {
		getUserCampus: (state) => state.userCampus, getRole: (state) => {
			return typeof state.role === 'number' ? state.role : 0
		}, getCampusList: (state) => state.campusList, getConferenceRoomList: (state) => state.conferenceRoomList,
	},
})
